package com.xiaocikuai.smallchunks.controller.Pay;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.xiaocikuai.smallchunks.config.WxPayAppConfig;
import com.xiaocikuai.smallchunks.entity.Pay.WX_Native_Request;
import com.xiaocikuai.smallchunks.entity.User.Duser;
import com.xiaocikuai.smallchunks.service.Pay.WxPayService;
import com.xiaocikuai.smallchunks.service.Transaction.TransactionServices;
import com.xiaocikuai.smallchunks.service.User.impl.DuserServiceImpl;
import com.xiaocikuai.smallchunks.utils.resultd.Resultd;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信支付控制器")
@RestController
@Slf4j
@RequestMapping("/api/pay")
@CrossOrigin
public class WX_PayController {

    @Autowired
    private WxPayService wxPayService;

//    @Resource
//    private Verifier verifier;
    @Resource
    private DuserServiceImpl duserService;


    @Resource
    private TransactionServices transactionService;


    @ApiOperation(value = "创建微信支付订单")
    @PostMapping("/createorder")
    public Resultd createOrder(
            @ApiParam(name = "token", value = "授权令牌", required = true)
            @RequestHeader("Authorization") String token,
            @ApiParam(name = "wxNativeRequest", value = "微信原生支付请求", required = true)
            @RequestBody WX_Native_Request wxNativeRequest) {
        try {
            transactionService.getOrderInfo(token, wxNativeRequest).get("id");
            // 订单号
            String out_trade_no = transactionService.getOrderInfo(token, wxNativeRequest).get("id").toString();
            // 支付金额，单位分
            String money = transactionService.getOrderInfo(token, wxNativeRequest).get("price").toString();
            Map result = new HashMap<>();
            switch (wxNativeRequest.getTag()) {
                case 1 -> {
                    result = wxPayService.nativePayV3(out_trade_no, money);
                    String code_url = (String) result.get("code_url");
                    System.out.println("Payment URL: " + code_url);

                    return Resultd.ok().data("info", code_url);
                }

                case 2 -> {
                    result = wxPayService.jsapiPayV3(out_trade_no, money, wxNativeRequest.getOpenId());
                    return Resultd.ok().data("info", result);
                }
                default -> System.out.println("其他情况");
            }
            return Resultd.error().data("info", "error");


        } catch (Exception e) {
            System.err.println("Error creating order: " + e.getMessage());
            e.printStackTrace();
            return Resultd.error().data("info",  e.getMessage());
        }
    }


    @PostMapping("/wxpaycallback")
    public String payCallBack(jakarta.servlet.http.HttpServletRequest request) throws IOException{
        log.info("开始回调");
        Map<String,String> resultMap = new HashMap<>();
        String signature = request.getHeader("Wechatpay-Signature");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String serial = request.getHeader("Wechatpay-Serial");
        String signType = request.getHeader("Wechatpay-Signature-Type");

        StringBuilder requestBody = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine())!= null) {
            requestBody.append(line);
        }
        try {
            // 配置微信支付证书和密钥
            RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(WxPayAppConfig.mchId)
                    .privateKeyFromPath(WxPayAppConfig.privateKeyPath)
                    .merchantSerialNumber(WxPayAppConfig.merchantSerialNumber)
                    .apiV3Key(WxPayAppConfig.apiV3key)
                    .build();

            // 构造 RequestParam
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(serial)
                    .nonce(nonce)
                    .signature(signature)
                    .timestamp(timestamp)
                    .signType(signType)
                    .body(requestBody.toString())
                    .build();

            // 初始化 NotificationParser 并验证签名
            NotificationParser parser = new NotificationParser(config);
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            log.info(transaction.toString());
            // 处理交易信息并保存到数据库
        if (transaction.getTradeState().toString().equals("SUCCESS")){
            //处理订单
            log.info("处理订单");
            transactionService.paysss(transaction.getOutTradeNo(), transaction.getAmount().getPayerTotal());
        } else {
            log.info("支付未成功");
        }

        } catch (Exception e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            resultMap.put("code","ERROR");
            resultMap.put("message",e.getMessage());
            return JSONObject.toJSONString(resultMap);
        }
        Map<String,String> result = new HashMap<>();
        result.put("code","SUCCESS");
        result.put("message","成功");
        log.info("回调结束");
        return JSONObject.toJSONString(result);
    }









}
